using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using AvaAI批量点评系统.Models;
using System.Drawing;

namespace AvaAI批量点评系统.Services
{
    /// <summary>
    /// 能力评语导出服务
    /// </summary>
    public class AbilityEvaluationExportService
    {
        /// <summary>
        /// 导出学生能力评语表格
        /// </summary>
        public async Task<string> ExportStudentAbilityEvaluationAsync(StudentAbilityEvaluation evaluation, string fileName = null)
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            fileName ??= $"{evaluation.StudentName}_能力评语_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx";
            var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName);

            using var package = new ExcelPackage();
            var worksheet = package.Workbook.Worksheets.Add($"{evaluation.StudentName} - 能力评语");

            // 设置表头
            SetupHeader(worksheet, evaluation.StudentName);

            // 设置表格列标题
            SetupColumnHeaders(worksheet);

            // 填充数据
            FillEvaluationData(worksheet, evaluation);

            // 设置样式
            ApplyStyles(worksheet, evaluation.EvaluationItems.Count);

            // 保存文件
            await package.SaveAsAsync(new FileInfo(filePath));

            return filePath;
        }

        /// <summary>
        /// 批量导出所有学生的能力评语表格
        /// </summary>
        public async Task<List<string>> ExportAllStudentsAbilityEvaluationsAsync(List<StudentCommentPreview> students)
        {
            var exportedFiles = new List<string>();

            foreach (var student in students)
            {
                if (student.AbilityEvaluation?.EvaluationItems?.Count > 0)
                {
                    var fileName = $"{student.StudentName}_能力评语_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx";
                    var filePath = await ExportStudentAbilityEvaluationAsync(student.AbilityEvaluation, fileName);
                    exportedFiles.Add(filePath);
                }
            }

            return exportedFiles;
        }

        /// <summary>
        /// 设置表头信息
        /// </summary>
        private void SetupHeader(ExcelWorksheet worksheet, string studentName)
        {
            // 合并单元格作为标题
            worksheet.Cells["A1:F1"].Merge = true;
            worksheet.Cells["A1"].Value = $"{studentName} - 能力评语表";
            worksheet.Cells["A1"].Style.Font.Size = 16;
            worksheet.Cells["A1"].Style.Font.Bold = true;
            worksheet.Cells["A1"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            worksheet.Cells["A1"].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
            worksheet.Row(1).Height = 30;

            // 添加生成时间
            worksheet.Cells["A2:F2"].Merge = true;
            worksheet.Cells["A2"].Value = $"生成时间: {DateTime.Now:yyyy年MM月dd日 HH:mm:ss}";
            worksheet.Cells["A2"].Style.Font.Size = 10;
            worksheet.Cells["A2"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            worksheet.Row(2).Height = 20;
        }

        /// <summary>
        /// 设置列标题
        /// </summary>
        private void SetupColumnHeaders(ExcelWorksheet worksheet)
        {
            var headers = new[] { "评价项目", "评价内容", "A-", "A", "A+", "评分" };
            
            for (int i = 0; i < headers.Length; i++)
            {
                var cell = worksheet.Cells[4, i + 1];
                cell.Value = headers[i];
                cell.Style.Font.Bold = true;
                cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                cell.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                cell.Style.Fill.BackgroundColor.SetColor(Color.LightGray);
                cell.Style.Border.BorderAround(ExcelBorderStyle.Thin);
            }

            worksheet.Row(4).Height = 25;
        }

        /// <summary>
        /// 填充评价数据
        /// </summary>
        private void FillEvaluationData(ExcelWorksheet worksheet, StudentAbilityEvaluation evaluation)
        {
            int currentRow = 5;
            string currentCategory = "";
            int categoryStartRow = currentRow;

            foreach (var item in evaluation.EvaluationItems)
            {
                // 如果是新的大类别，处理合并单元格
                if (item.Category != currentCategory)
                {
                    // 如果不是第一个类别，合并前一个类别的单元格
                    if (!string.IsNullOrEmpty(currentCategory) && currentRow > categoryStartRow)
                    {
                        var categoryCell = worksheet.Cells[categoryStartRow, 1, currentRow - 1, 1];
                        categoryCell.Merge = true;
                        categoryCell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                    }

                    currentCategory = item.Category;
                    categoryStartRow = currentRow;
                }

                // 填充数据
                worksheet.Cells[currentRow, 1].Value = item.Category;
                worksheet.Cells[currentRow, 2].Value = item.SubCategory;
                worksheet.Cells[currentRow, 3].Value = item.LevelAMinus;
                worksheet.Cells[currentRow, 4].Value = item.LevelA;
                worksheet.Cells[currentRow, 5].Value = item.LevelAPlus;
                worksheet.Cells[currentRow, 6].Value = item.SelectedLevel;

                // 高亮选中的等级
                HighlightSelectedLevel(worksheet, currentRow, item.SelectedLevel);

                currentRow++;
            }

            // 处理最后一个类别的合并
            if (!string.IsNullOrEmpty(currentCategory) && currentRow > categoryStartRow)
            {
                var categoryCell = worksheet.Cells[categoryStartRow, 1, currentRow - 1, 1];
                categoryCell.Merge = true;
                categoryCell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
            }
        }

        /// <summary>
        /// 高亮选中的等级
        /// </summary>
        private void HighlightSelectedLevel(ExcelWorksheet worksheet, int row, string selectedLevel)
        {
            int columnIndex = selectedLevel switch
            {
                "A-" => 3,
                "A" => 4,
                "A+" => 5,
                _ => 4
            };

            var cell = worksheet.Cells[row, columnIndex];
            cell.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
            cell.Style.Fill.BackgroundColor.SetColor(Color.LightYellow);
            cell.Style.Font.Bold = true;

            // 评分列也高亮
            var gradeCell = worksheet.Cells[row, 6];
            gradeCell.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
            gradeCell.Style.Fill.BackgroundColor.SetColor(Color.LightGreen);
            gradeCell.Style.Font.Bold = true;
            gradeCell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        }

        /// <summary>
        /// 应用样式
        /// </summary>
        private void ApplyStyles(ExcelWorksheet worksheet, int dataRowCount)
        {
            // 设置列宽
            worksheet.Column(1).Width = 15;  // 评价项目
            worksheet.Column(2).Width = 15;  // 评价内容
            worksheet.Column(3).Width = 30;  // A-
            worksheet.Column(4).Width = 30;  // A
            worksheet.Column(5).Width = 30;  // A+
            worksheet.Column(6).Width = 10;  // 评分

            // 设置数据区域边框
            var dataRange = worksheet.Cells[4, 1, 4 + dataRowCount, 6];
            dataRange.Style.Border.Top.Style = ExcelBorderStyle.Thin;
            dataRange.Style.Border.Left.Style = ExcelBorderStyle.Thin;
            dataRange.Style.Border.Right.Style = ExcelBorderStyle.Thin;
            dataRange.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;

            // 设置数据行高度和文本换行
            for (int row = 5; row <= 4 + dataRowCount; row++)
            {
                worksheet.Row(row).Height = 40;
                for (int col = 1; col <= 6; col++)
                {
                    worksheet.Cells[row, col].Style.WrapText = true;
                    worksheet.Cells[row, col].Style.VerticalAlignment = ExcelVerticalAlignment.Top;
                    
                    if (col == 1 || col == 6) // 评价项目和评分列居中
                    {
                        worksheet.Cells[row, col].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                    }
                }
            }

            // 设置整个工作表的字体
            worksheet.Cells.Style.Font.Name = "微软雅黑";
            worksheet.Cells.Style.Font.Size = 10;
        }
    }
}
